package com.dailyblue.smbms.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter("/*")
public class IsLoginFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("开始校验用户是否登陆");
        // 如果访问的是登陆接口（login.html、user_login）
        String uri = request.getRequestURI();
        System.out.println("用户访问的接口是：" + uri);
        if (uri.indexOf("login.html") != -1 || uri.indexOf("user_login") != -1 || uri.indexOf(".js") != -1 || uri.indexOf(".css") != -1 || uri.indexOf(".png") != -1) {
            System.out.println("访问登陆接口或者前端css,js，放行");
            chain.doFilter(request, response);
        }
        // 判断用户是否登陆
        HttpSession session = request.getSession();
        Object info = session.getAttribute("USER_INFO");
        System.out.println("用户的登陆信息是：" + info);
        if (info == null) {
            System.out.println("用户没有登陆，访问login.html页面");
            response.sendRedirect("login.html#error=2");
            //request.getRequestDispatcher("login.html#error=2").forward(request, response);
            //return;
        } else {
            System.out.println("用户已登陆，放行");
            chain.doFilter(request, response);
        }
    }
}